﻿using Biz;
using BusinessLayer.Biz;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BusinessLayer.Dal
{
    public class OrderDal
    {
        DatabaseContext db;
        public OrderDal( /* DatabaseContext db */ )
        {
            this.db = DatabaseContext.DB;
        }
        public List<Order> GetAll()
        {
           return db.Orders.ToList();
        }
        public List<Order> GetByCondition(DateTime from,DateTime to,int status)
        {
            List<Order> orders = db.Orders.Where(o => o.Time >= from && o.Time <= to).ToList();
            if (status >= 0)
            {
                orders = orders.Where(o => (int)o.Status == status).ToList();
            }
            return orders;
        }
        public void Insert(Order order,Cart cart)
        {
            db.Orders.Add(order);
            db.SaveChanges();
            foreach (var item in cart.ListItem)
            {
                OrderedProduct orderDetail = new OrderedProduct();
                orderDetail.Product = item.Product;
                orderDetail.Quantity = item.Count;
                orderDetail.Price = (int)item.CurrentPrice;
                orderDetail.Order = order;
                orderDetail.Insert();
                Unsold unsold = new Unsold();
                unsold.Product = item.Product;
                unsold.QuantityExport = item.Count;
                unsold.QuantityUnsold = unsold.GetQuantityByProduct(item.Product) - item.Count;
                unsold.QuantityImport = 0;
                unsold.Time = DateTime.Now;
                unsold.Insert();
            }
        }

        public void Update(Order order)
        {
            db.Entry(order).State = EntityState.Modified;
            db.SaveChanges();
        }
    }
}
